<?php

/*$query = new YoutubeQuery();
$query->setQuery("el tio la vara");
$query->setPageSize(10);
$page = $query->getPage(4);
$page->getTotalResults();
*/

class YoutubeQuery{
	private $pageSize;
	private $query;
	
	function YoutubeQuery(){
		$this->pageSize = 10;
	}
	
	public function setQuery($query){
		$this->query = urlencode($query);
	}
	
	public function setPageSize($pageSize){
		$this->pageSize = $pageSize;
	}
	
	public function getPage($page){
		$startIndex = ($this->pageSize * ($page-1))+1;
		$maxResults = $this->pageSize;
		$url = "http://gdata.youtube.com/feeds/api/videos?vq=".$this->query."&racy=include&orderby=relevance&max-results=".$maxResults."&start-index=".$startIndex;
		$ch = curl_init();
  		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL,$url);
        $res = curl_exec ($ch);
        curl_close($ch);
        
        $doc = new DOMDocument();
        $doc->loadXML($res);
        
        $totalResults = $doc->getElementsByTagName("totalResults")->item(0)->nodeValue;
        $videos = $doc->getElementsByTagName("entry");
        
        $result = array();
        $result['pages'] = ceil($totalResults/$this->pageSize);
        $result['pages'] = $result['pages'] < 100 ? $result['pages']: 100;
        $result['videos'] = array();
		foreach($videos as $video){
			$videoArr = array();
			$id = $video->getElementsByTagName("id")->item(0);
			$id = $id->nodeValue;
			$videoId = explode("/",$id);
			$videoArr['id'] = $videoId[count($videoId)-1];
			
			$title = $video->getElementsByTagName("title")->item(0);
			$videoArr['title'] = $title->nodeValue;
			
			$thumb = $video->getElementsByTagName("thumbnail")->item(0);
			
			$videoArr['thumbnail'] = $thumb->getAttribute("url");
			
			$result['videos'][] = $videoArr;
			
		}
        return $result;
	}
	
	
}

?>